package managedbeans;

import java.io.Serializable;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import factoryService.FactoryService;
import javax.servlet.http.*;
import javax.faces.context.*;
import model.Usuario;

@ManagedBean
@SessionScoped
public class BeanLogin implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 8618410717042752868L;

	private Usuario usuario;
	private String lembrar;
	private Boolean checkLembrar;

	public BeanLogin() {
		if (usuario == null) {
			usuario = new Usuario();
		}
		checkCookie();
	}

	// DAO FACTORY...

	public String login() throws Exception {

		boolean logado = false;
		HttpSession session = (HttpSession) FacesContext.getCurrentInstance()
				.getExternalContext().getSession(false);
		logado = FactoryService.getUsuarioService().autentica(
				this.usuario.getEmail(), this.usuario.getSenha());

		if (logado) {
			session.setAttribute("user", logado);
			FacesContext
					.getCurrentInstance()
					.getExternalContext()
					.getSessionMap()
					.put("usuario",
							FactoryService.getUsuarioService()
									.procuraUnicoUsuario(usuario.getEmail(),
											usuario.getSenha()));
			CheckLogin();
			// rp.sendRedirect(rq.getContextPath() + "/principal.xhtml");
			return "/principal.xhtml";

		} else {
			session = (HttpSession) FacesContext.getCurrentInstance()
					.getExternalContext().getSession(false);
			session.setAttribute("user", null);
			session.removeAttribute("user");
			FacesContext.getCurrentInstance().addMessage(
					null,
					new FacesMessage(FacesMessage.SEVERITY_ERROR,
							"Sample error message",
							"Senha e E-mail incorretos."));
			// rp.sendRedirect(rq.getContextPath() + "/login.xhtml");
			usuario = new Usuario();
			return "";
			// return "/login.xhtml";
		}
	}

	public String logout() {
		// HttpServletRequest rq = (HttpServletRequest)
		// FacesContext.getCurrentInstance().getExternalContext().getRequest();

		// HttpServletResponse rp = (HttpServletResponse)
		// FacesContext.getCurrentInstance().getExternalContext().getResponse();
		FacesContext facesContext = FacesContext.getCurrentInstance();
		HttpSession session = (HttpSession) facesContext.getExternalContext()
				.getSession(false);
		session.invalidate();
		// try {
		// rp.sendRedirect(rq.getContextPath() + "/login.xhtml");
		// } catch (IOException e) {
		// e.printStackTrace();
		// }
		//usuario = new Usuario();
		return "/login.xhtml";
	}

	public void CheckLogin() {

		if (checkLembrar == true) {
			FacesContext facesContext = FacesContext.getCurrentInstance();
			// Save the userid and password in a cookie
			Cookie btuser = new Cookie("btuser", usuario.getEmail());
			Cookie btpasswd = new Cookie("btpasswd", usuario.getSenha());
			if (checkLembrar == false) {
				lembrar = "false";
			} else {
				lembrar = "true";
			}
			Cookie btremember = new Cookie("btremember", lembrar);
			btuser.setMaxAge(3600);
			btpasswd.setMaxAge(3600);

			((HttpServletResponse) facesContext.getExternalContext()
					.getResponse()).addCookie(btuser);
			((HttpServletResponse) facesContext.getExternalContext()
					.getResponse()).addCookie(btpasswd);
			((HttpServletResponse) facesContext.getExternalContext()
					.getResponse()).addCookie(btremember);
		}
	}

	public void checkCookie() {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		String cookieName = null;
		Cookie cookie[] = ((HttpServletRequest) facesContext
				.getExternalContext().getRequest()).getCookies();
		if (cookie != null && cookie.length > 0) {
			for (int i = 0; i < cookie.length; i++) {
				cookieName = cookie[i].getName();

				if (cookieName.equals("btuser")) {
					usuario.setEmail(cookie[i].getValue());
				} else if (cookieName.equals("btpasswd")) {
					usuario.setSenha(cookie[i].getValue());
				} else if (cookieName.equals("btremember")) {
					lembrar = cookie[i].getValue();
					if (lembrar.equals("false")) {
						checkLembrar = false;
					} else if (lembrar.equals("true")) {
						checkLembrar = true;
					}
				}
			}

		}
	}

	public Usuario getUsuario() {
		return usuario;
	}

	public void setUsuario(Usuario usuario) {
		this.usuario = usuario;
	}

	public String getLembrar() {
		return lembrar;
	}

	public void setLembrar(String lembrar) {
		this.lembrar = lembrar;
	}

	public Boolean getCheckLembrar() {
		return checkLembrar;
	}

	public void setCheckLembrar(Boolean checkLembrar) {
		this.checkLembrar = checkLembrar;
	}

}
